//
//  CTCResponderVC.m
//  ConsultantVersion
//
//  Created by 李小龙 on 2017/3/24.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "CTCResponderVC.h"
#import "CTCResponderCell.h"
#import "CTCLoginViewController.h"
#import "CTCResponderDetailVC.h"
#import "CTCBirdShowViewController.h"

@interface CTCResponderVC ()
@property (nonatomic, strong) NSMutableArray *questionArr;
/** 页数 */
@property (nonatomic, assign) NSInteger lastIndex;

/** <#strong属性注释#> */
@property (nonatomic, strong) UIButton *rightBtn;
@end

@implementation CTCResponderVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupTableView];
    
    [self loadNew];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadNew) name:kReloadIndexPathSelectedRepaidListNotification object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    ReleaseConfirm *defaultConfirm = [ReleaseConfirm DefultInstance];
    if (defaultConfirm.isShowUpdate) {
        [defaultConfirm showUpdateAlert];
    }
    
    
    if ([CTCUserModel shareUser].login) {
        [CTCBirdShowViewController display];
    }
    
    [self getTabBarRedBadgeData];
    
    [self showRepaidConsultRedView];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.questionArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CTCResponderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CTCResponderCell" forIndexPath:indexPath];
    cell.questionModel = self.questionArr[indexPath.section];
    cell.responderBtnBlock = ^(CTCQuestionModel *questionModel){
        [self jumpToDetailIndexPath:indexPath];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 
    [self jumpToDetailIndexPath:indexPath];
    
}

- (void)loadNew
{
    self.lastIndex = 1;
    [self.questionArr removeAllObjects];
    [self getResponderList];
}


- (void)getResponderList
{
    if (![CTCUserModel shareUser].login) {
        CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
        MPWeakSelf(self);
        vc.loginSuccess = ^(){
            [weakself loadNew];
        };
        [self presentViewController:vc animated:YES completion:nil];
        
        return;
    }
    
    NSMutableDictionary *paramsDic = [NSMutableDictionary dictionary];
    paramsDic[@"pageIndex"] = @(self.lastIndex);
    paramsDic[@"pageEnd"] = @(self.lastIndex+9);
    
    
    DeLog(@"请求的参数----paramsDic:%@",paramsDic);
    DeLog(@"头部参数---cookieID:%@",[CTCUserModel shareUser].cookieID);
    
//    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kResponderListUrl
           parameters:paramsDic
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  DeLog(@"response %@", responseObject);
                  
                  [self stopRefresh];
                  [MBProgressHUD hideHUD];
                  CTCResponderQuestionListModel *listModel = [CTCResponderQuestionListModel yy_modelWithJSON:responseObject];
                  
                  NSInteger code = [listModel.code integerValue];
                  if (code == 1) {
                      
                      
                      if (!listModel.questionArr.count) {
                          self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
                          return ;
                      }
                      
                      [self.questionArr addObjectsFromArray:listModel.questionArr];
                    
                      self.lastIndex += self.questionArr.count;
                      
                      [self.tableView reloadData];
                  }
                  
                  else if (code == 2) {
                      [MBProgressHUD showErrorMessage:listModel.des];
                      CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
                      MPWeakSelf(self);
                      vc.loginSuccess = ^(){
                          [weakself loadNew];
                      };
                      [self presentViewController:vc animated:YES completion:nil];
                  } else {
                      [MBProgressHUD showErrorMessage:listModel.des];
                  }
                  
              } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  DeLog(@"请求的参数error:%@",error);
                  [self stopRefresh];
                  if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }                 
              }];
}



- (void)stopRefresh
{
    !self.tableView.mj_header.isRefreshing ? : self.tableView.mj_header.endRefreshing;
    !self.tableView.mj_footer.isRefreshing ? : self.tableView.mj_footer.endRefreshing;
}


- (void)rightBarButtonItemClick
{
    [self performSegueWithIdentifier:@"CTCResponderHistoryVC" sender:nil];

    
}


- (void)jumpToDetailIndexPath:(NSIndexPath *)indexPath
{
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"CTCResponderVC" bundle:nil];
    CTCResponderDetailVC *vc = [story instantiateViewControllerWithIdentifier:@"CTCResponderDetailVC"];
    
    CTCQuestionModel *model = self.questionArr[indexPath.section];
    vc.questionModel = model;
    vc.fromType = ResponderDetailFromTypeRapid;
    vc.responderSuccessBlock = ^(){
        model.status = @"1";
        [self.tableView reloadSections:[[NSIndexSet alloc]initWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
        
    };
    [self.navigationController pushViewController:vc animated:YES];
}



- (void)setupTableView
{
    self.tableView.estimatedRowHeight = 200;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.sectionHeaderHeight = 10;
    self.tableView.sectionFooterHeight = 0;
    self.tableView.contentInset = UIEdgeInsetsMake(11-35, 0, 0, 0);
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNew)];
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(getResponderList)];
    
}

- (void)showRepaidConsultRedView
{
    if (![CTCUserModel shareUser].login) {
        return;
    }
    
    [RequestTool POST:kRapidConsultRedUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"responseObject %@", responseObject);
        
        if ([responseObject[@"code"] integerValue] == 1) {
            if ([responseObject[@"data"] integerValue] == 1) {
                [self.rightBtn showBadge];
                [self.tabBarController.tabBar.items[0] showBadge];
            }
            else {
                [self.rightBtn hidenBadge];
                [self.tabBarController.tabBar.items[0] hidenBadge];
            }
        }
        else {
            [MBProgressHUD showInfoMessage:responseObject[@"des"]];
            if ([responseObject[@"code"] integerValue] == 2) {
                CTCLoginViewController *vc = [CTCLoginViewController viewControllerFromStoryboard];
                MPWeakSelf(self);
                vc.loginSuccess = ^(){
                    [weakself loadNew];
                };
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error %@", error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];
}


- (NSMutableArray *)questionArr
{
    if (!_questionArr) {
        _questionArr = [NSMutableArray array];
    }
    
    return _questionArr;
}


- (UIButton *)rightBtn
{
    if (!_rightBtn) {
        _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightBtn.frame = CGRectMake(0, 0, 31/2, 37/2);
        [_rightBtn setBackgroundImage:[UIImage imageNamed:@"consult-history"] forState:UIControlStateNormal];
        [_rightBtn addTarget:self action:@selector(rightBarButtonItemClick) forControlEvents:UIControlEventTouchUpInside];
        
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:_rightBtn];
    }
    return _rightBtn;
}



- (void)getTabBarRedBadgeData
{
    [RequestTool POST:kTabBarRedBadgeUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"kTabBarRedStatusURL---responseObject %@", responseObject);
        
        if ([responseObject[@"code"] integerValue] == 1) {
            
            if ([responseObject[@"data"][@"rapidRed"] integerValue]) {
                [self.tabBarController.tabBar.items[0] showBadge];
            } else {
                [self.tabBarController.tabBar.items[0] hidenBadge];
            }
            
            if (([responseObject[@"data"][@"oneRed"]  integerValue]) ||([responseObject[@"data"][@"lineDownRed"]  integerValue])) {
                [self.tabBarController.tabBar.items[1] showBadge];
            } else {
                [self.tabBarController.tabBar.items[1] hidenBadge];
            }
            
            
            
        }
        else {
            [MBProgressHUD showInfoMessage:responseObject[@"des"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error %@", error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];
}

@end
